package cc.rengu.igas.channel.upac.core.service.trans;


import cc.rengu.igas.channel.upac.common.constant.UpacParamConstant;
import cc.rengu.igas.channel.upac.common.constant.UpacTreeNodeConstant;
import cc.rengu.igas.channel.upac.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.upac.common.enums.UpacProdEnum;
import cc.rengu.igas.channel.upac.common.util.UpacSecurityUtil;
import cc.rengu.igas.channel.upac.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.upac.core.service.base.TokenPayService;
import cc.rengu.igas.channel.upac.facade.bean.CustomerInfo;
import cc.rengu.igas.channel.upac.facade.bean.TokenPayInfo;
import cc.rengu.igas.channel.upac.facade.request.TokenPayOpenByOrderIdRequest;
import cc.rengu.igas.channel.upac.facade.response.TokenPayOpenByOrderIdResponse;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.DstChannelCfg;
import cc.rengu.oltp.service.common.entity.DstChannelInfo;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.util.HashMap;
import java.util.Map;

/**
 * 银联全渠道订单号获取标记服务 on 2019/10/8.
 */
public class TokenApplyService extends TokenPayService {


    @Override
    protected Object beforeBizProcess() throws Exception {
        TokenPayOpenByOrderIdRequest tokenPayOpenByOrderIdRequest = new TokenPayOpenByOrderIdRequest();
        ConvertUtil.convertOutput(tokenPayOpenByOrderIdRequest);
        return tokenPayOpenByOrderIdRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        int iReturnCode = 0;
        String acctEncFlag = xmlTreeUtil.getXmlTreeStringValue(UpacTreeNodeConstant.ACCT_ENC_FLAG);
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        TokenPayOpenByOrderIdResponse tokenPayOpenByOrderIdResponse = new TokenPayOpenByOrderIdResponse();
        TokenPayOpenByOrderIdRequest tokenPayOpenByOrderIdRequest = (TokenPayOpenByOrderIdRequest) request;
        DstChannelInfo dstChannelInfo = (DstChannelInfo) xmlTreeUtil.getXmlTreeObjectValue(UpacTreeNodeConstant.DST_CHANNEL_INFO, DstChannelInfo.class);
        /* 获取通道配置信息 */
        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(UpacTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);
        if (null == dstChannelCfg) {
            rglog.error("获取通道<{}><{}>配置信息失败!", ChannelEnum.UPAC.getChannelType(), ChannelEnum.UPAC.getChannelDesc());
            throw new BizException(RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespCode(), RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespDesc());
        }
        ConvertUtil.convertInput(tokenPayOpenByOrderIdRequest);

        JSONObject jsonObject = JSON.parseObject(dstChannelCfg.getOtherConfParam());
        TokenPayInfo tokenPayInfoReq = new TokenPayInfo();
        tokenPayInfoReq.setTrId(jsonObject.getString("trId"));
        tokenPayInfoReq.setTokenType(jsonObject.getString("tokenType"));
        packageTokenPayInfo(tokenPayInfoReq);
        xmlTreeUtil.setXmlTreeStringValue(UpacTreeNodeConstant.txnType, "79");
        xmlTreeUtil.setXmlTreeStringValue(UpacTreeNodeConstant.txnSubType, "05");
        xmlTreeUtil.setXmlTreeStringValue(UpacTreeNodeConstant.bizType, UpacProdEnum.TOKEN_PAY.getProdCode());
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, tokenPayOpenByOrderIdRequest.getHeader().getTxnNum());
        iReturnCode = schedule.callService(dstChannelInfo.getDstServiceName(), 0);
        if (98 == iReturnCode) {
            rglog.error("调用银联全渠道服务<{}>超时，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            tokenPayOpenByOrderIdResponse.setRespCode(OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode());
            tokenPayOpenByOrderIdResponse.setRespDesc(OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespDesc());
            chnlBizResponse.setResult(tokenPayOpenByOrderIdResponse);
            return chnlBizResponse;
        } else if (0 != iReturnCode) {
            rglog.error("调用银联全渠道服务<{}>失败，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }
        ConvertUtil.convertOutput(tokenPayOpenByOrderIdResponse);
        tokenPayOpenByOrderIdResponse.setRespCode(convertRespCode(tokenPayOpenByOrderIdResponse.getRespCode()));
        if (tokenPayOpenByOrderIdResponse.getPayAcctNo() != null) {
            if ("Y".equals(acctEncFlag)) {
                rglog.error("配置账户加密，解密账号");
                tokenPayOpenByOrderIdResponse.setPayAcctNo(descryptData(tokenPayOpenByOrderIdResponse.getPayAcctNo()));
            }
        }
        String tokenPayData = xmlTreeUtil.getXmlTreeStringValue(UpacTreeNodeConstant.tokenPayData);
        if (tokenPayData != null) {
            TokenPayInfo tokenPayInfo = (TokenPayInfo) convertKvStr2Bean(tokenPayData, TokenPayInfo.class);
            tokenPayOpenByOrderIdResponse.setTokenPayInfo(tokenPayInfo);
        }
        String customerInfoBase64Str = xmlTreeUtil.getXmlTreeStringValue(UpacTreeNodeConstant.customerInfo);
        if (customerInfoBase64Str != null) {
            Map<String, String> customer = new HashMap<>();
            CustomerInfo customerInfo = new CustomerInfo();
            String customerInfoStr = new String(Base64.decodeBase64(customerInfoBase64Str));
            rglog.info("customerInfoStr=[{}]", customerInfoStr);
            customer = UpacSecurityUtil.convertResultString2Map(customerInfoStr);
            if (customer.get("customerNm") != null) {
                customerInfo.setCustName(customer.get("customerNm"));
            }
            if (customer.get("certifTp") != null) {
                customerInfo.setCertType(customer.get("certifTp"));
            }
            if (customer.get("certifId") != null) {
                customerInfo.setCertNo(customer.get("certifId"));
            }
            if (customer.get("encryptedInfo") != null) {
                String encStr = descryptData(customer.get("encryptedInfo"));
                Map<String, String> encMap = new HashMap<>();
                encMap = UpacSecurityUtil.convertResultString2Map(encStr);
                if (encMap.get("phoneNo") != null) {
                    customerInfo.setPhoneNo(encMap.get("phoneNo"));
                }
                if (encMap.get("expired") != null) {
                    customerInfo.setExpiryDate(encMap.get("expired"));
                }
            }
            tokenPayOpenByOrderIdResponse.setCustomerInfo(customerInfo);
        }

        chnlBizResponse.setResult(tokenPayOpenByOrderIdResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        TokenPayOpenByOrderIdResponse tokenPayOpenByOrderIdResponse = (TokenPayOpenByOrderIdResponse) response.getResult();
        ConvertUtil.convertInput(tokenPayOpenByOrderIdResponse);
    }
}
